package com.ioi.weixin;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Joiner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * 微信API接口调用基础类，提供调用微信接口的通用基础能力
 *
 * @author LILIBO
 * @since 2024/6/3
 */
public class BaseApi {

    private static final Logger log = LogManager.getLogger(BaseApi.class);

    /**
     * 微信API接口配置文件
     */
    private static final String config = "weixinapi.properties";

    public static String appid = null;
    public static String secret = null;

    /*
     * 静态代码块，类创建时执行
     */
    static {
        // 加载配置文件
        loadConfig();
    }

    /**
     * 加载配置文件
     */
    private static void loadConfig() {
        Properties properties = new Properties();
        try {
            properties.load(BaseApi.class.getClassLoader().getResourceAsStream(config));
            appid = properties.getProperty("appid");
            secret = properties.getProperty("secret");
        } catch (IOException e) {
            log.error(e.fillInStackTrace());
        }
    }

    /**
     * 通过GET方式调用API接口（拼接到URL上的查询参数）
     *
     * @param url
     * @param params
     * @return
     */
    public JSONObject apiGetQuery(String url, Map<String, Object> params) {
        String join = Joiner.on("&").withKeyValueSeparator("=").join(params);
        String body; // API接口响应内容
        try (HttpResponse resp = HttpRequest.get(url + "?" + join).execute()) {
            body = resp.body();
        }
        return JSON.parseObject(body);
    }

    /**
     * 通过GET方式调用API接口
     *
     * @param url
     * @param params
     * @return
     */
    public JSONObject apiGet(String url, Map<String, Object> params) {
        String body; // API接口响应内容
        try (HttpResponse resp = HttpRequest.get(url).body(JSON.toJSONString(params)).execute()) {
            body = resp.body();
        }
        return JSON.parseObject(body);
    }

    /**
     * 通过POST方式调用API接口
     *
     * @param url
     * @param params
     * @return
     */
    public JSONObject apiPost(String url, Map<String, Object> params) {
        String body; // API接口响应内容
        try (HttpResponse resp = HttpRequest.post(url).body(JSON.toJSONString(params)).execute()) {
            body = resp.body();
        }
        return JSON.parseObject(body);
    }

}
